package top.yoahh.security.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import top.yoahh.system.entity.SysRole;
import top.yoahh.system.entity.SysUser;
import top.yoahh.system.mapper.SysRoleMapper;
import top.yoahh.system.mapper.SysUserMapper;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class UserService implements UserDetailsService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("正在登录的用户:{}", username);
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(SysUser::getUsername, username);
        SysUser sysUser = sysUserMapper.selectOne(queryWrapper);
        if(sysUser == null){
            throw new  UsernameNotFoundException("用户名不存在");
        }

        // 根据用户ID去查询对应的用户角色
        List<SysRole> roleList = sysRoleMapper.queryByUserId(sysUser.getId());
        List<GrantedAuthority> grantedAuthorityList = new ArrayList<>();
        roleList.forEach(sysRole -> {
            GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(sysRole.getCode());
            grantedAuthorityList.add(grantedAuthority);
        });

        return new User(sysUser.getUsername(),sysUser.getPassword(),grantedAuthorityList);
    }
}
